﻿using System;
using System.Collections.Generic;

public class EnemyFSM<T>
{
    static EnemyFSM()
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException("T must be anenumerated type!");
        }
    }
    private T currentType;
    private IState<T> currentState;
    private Dictionary<T, List<IState<T>>> states = new Dictionary<T, List<IState<T>>>();

    public EnemyFSM(Dictionary<T, List<IState<T>>> states, T initType)
    {
        this.states = states;
        currentType = initType;
        TransitionState(initType);
    }
    public void OnUpdate()
    {
        currentState.OnUpdate();
    }
    /// <summary>
    /// 状态转换
    /// </summary>
    /// <param name="toType"></param>
    /// <param name="index">-1代表随机行为</param>
    public void TransitionState(T toType, int index = -1)
    {
        if (toType != null && states.ContainsKey(toType) && states[toType].Count > index)
        {
            if (currentState != null)
            {
                currentState.OnExit(toType);
            }
            int randomIndex = index == -1 ? UnityEngine.Random.Range(0, index) : index;
            currentState = states[toType][randomIndex];
            currentState.OnEnter(currentType);
            currentType = toType;
        }
    }
    public T GetCurType()
    {
        return currentType;
    }
}
